<?php
/**
  * xml RPC kit
  * simplified for commentor as
  * it's using PHP, the payload
  * carries flattened PHP data such as array/objects.
 * @author bbqq
 * @copyright 2010 qstufie.com
 * @package com.sprpc.handler
  */
class SPRPC_Handler_Base
{
    /**
     * the token to validate with
     * @var token
     */
    protected $_token = null;

    // payload str
    protected $_payload = null;

    // checksum str
    protected $_checksum = null;


    // compose xml
    protected function _compose($type, $payload)
    {
        $payload  = base64_encode(serialize($payload));
        $checksum = $this->_mkchecksum($payload, $this->_token);
        // compose it with type
        return '<?xml version="1.0" encoding="utf-8"?>' .
               '<' . $type . '>' .
               '<payload>' . $payload . '</payload>' .
               '<checksum>' . $checksum . '</checksum>' .
               '</' . $type . '>';

    }// end _compose


    // compose error xml
    protected function _error(Exception $e)
    {
        echo '<?xml version="1.0" encoding="utf-8"?>' .
             '<error>' .
             '<code>' . $e->getCode() . '</code>' .
             '<message>' . $e->getMessage() . '</message>' .
             '</error>';
        exit;

    }// end _error


    /**
     * parse xml
     * @param str $data
     * @return void
     */
    protected function _parse($data)
    {
        $xml = SPRPC_Utility_Xml::readString($data);
        $this->_payload  = (string) $xml->payload;
        $this->_checksum = (string) $xml->checksum;

    }// end _parse


    /**
     * parse error xml
     */
    protected function _parseError($data)
    {
        $xml     = SPRPC_Utility_Xml::readString($data);
        $code    = (int) $xml->code;
        $message = (string) $xml->message;
        throw new Exception($message, $code);

    }// end _parseError


    /**
     * extract the payload
     * @return array
     */
    protected function _extract()
    {
        $arTmp = unserialize(base64_decode($this->_payload));
        if (!isset($arTmp['method'])) {
            $e = new Exception('Method not defined', 200);
            $this->_error($e);
        }

        if (!isset($arTmp['args'])) {
            $arTmp['args'] = array();
        }

        return $arTmp;

    }// end _extract


    /**
     * make checksum
     * @param str $pl payload
     * @param str $token the token
     * @return str checksum
     */
    protected function _mkchecksum($pl, $token)
    {
        return md5($pl . '>>>>' . $token);

    }// end _mkchecksum

}// end SPRPC_Handler_Base
?>